package com.servlet;

import com.bean.Person;
import com.bean.Student;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/demo01.do")
public class Demo01Servlet extends BaseServlet {
    protected void servletContext(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ServletContext servletContext = request.getServletContext();
        servletContext.setAttribute("name1", "value1");
        servletContext.setAttribute("name1", "value2");
        servletContext.removeAttribute("name1");
//        HttpSessionBindingListener
//        HttpSessionActivationListener
    }


    protected void session(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        session.setAttribute("session1", "value1");
        session.setAttribute("session1", "value2");
        session.removeAttribute("session1");
    }

    protected void request(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setAttribute("request1", "value1");
        request.setAttribute("request1", "value2");
        request.removeAttribute("request1");
    }

    protected void addPersonToSession(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Person person = new Person();
        person.setAge(18);
        person.setName("小明");
        person.setSex("男");
        request.getSession().setAttribute("person", person);
    }

    protected void removePersonFromSession(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getSession().removeAttribute("person");
    }

    protected void addStudentToSession(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("当前SessionId:" + request.getSession().getId());
        request.getSession().setAttribute("student", new Student(1, "小明", 18));
    }

    protected void getStudentFromSession(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("当前SessionId:" + request.getSession().getId());
        Object student = request.getSession().getAttribute("student");
        System.out.println(student);
    }


}
